//
//  SettingViewController.m
//  TTAddressBook
//
//  Created by WangJuan on 11-12-30.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "SettingViewController.h"
#import "CommTools.h"
#import "HelpViewController.h"
#import "AboutViewController.h"
#import "FeedbackViewController.h"
#import "imagePath.h"
#import "SettingConstants.h"
#import "MyClass.h"
#import "FirstLauchViewController.h"

@implementation SettingViewController
@synthesize tableViewIb;
@synthesize accountTableCell;
@synthesize pictureButton;
@synthesize nameLabel;
@synthesize numLabel;



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
    if (self) 
    {
        self.title = @"设置";
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (IBAction)pictureButtonAction:(id)sender
{
//    UIActionSheet *menu = [[UIActionSheet alloc]
//                           initWithTitle: @"编辑照片"
//                           delegate:self
//                           cancelButtonTitle:@"取消"
//                           destructiveButtonTitle:nil
//                           otherButtonTitles: @"相册图片", @"拍照", nil];
//    
//    [menu showInView:self.view.window];
//    [menu release];
}

- (IBAction)labelButtonAction:(id)sender 
{
//    AccountSettingViewController *accountSettingView = [[AccountSettingViewController alloc] initWithNibName:@"AccountSettingViewController" bundle:nil];
//    [self.navigationController pushViewController:accountSettingView animated:YES];
//    [accountSettingView release];
}

- (void)activateEvent   //一键激活
{
    //调用短信界面发送短信	
    BOOL canSendSMS = [CommTools callMessageCompose:self bodyOfMessage:@"test" numOfMessage:@"13811059125"];
    
	if ( !canSendSMS ) //4.0以下版本不支持在程序中调用短信界面
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"不支持发送短信功能，请手动编辑短信" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        alert.tag = SmsNotSupportAlertTag;
        
        [alert show];
        [alert release];
    }
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    tableViewIb.delegate = self;
	tableViewIb.dataSource = self;

    
    isActivated = YES;  //Test
        
//    UIBarButtonItem *back = [[UIBarButtonItem alloc] init];
//    back.title = @"返回";
//    self.navigationItem.backBarButtonItem = back;
//    [back release];
    
//    if ([[[UIDevice currentDevice] systemVersion] doubleValue] >= 5.0)
//    {
//        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:UIContacts_contacts_navigationBar] forBarMetrics:0];
//    }
//    else
//    {
//        self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:0.0/255 green:130.0/255 blue:180.0/255 alpha:0.8];
//    }
//    
    tableViewIb.backgroundColor = [UIColor clearColor];
    UIImageView *backgroundView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
    backgroundView.image = [UIImage imageNamed:kSettingBackGroundPng];
    [self.view addSubview:backgroundView];
    [self.view sendSubviewToBack:backgroundView];
    [backgroundView release];
}

- (void)viewDidAppear:(BOOL)animated
{

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [tableViewIb reloadData];
}
-(void)viewWillDisappear:(BOOL)animated{
    
}
- (void)viewDidUnload
{
    [self setTableViewIb:nil];
    [self setAccountTableCell:nil];
    [self setNameLabel:nil];
    [self setNumLabel:nil];
    [self setPictureButton:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc 
{
    [tableViewIb release];
    [accountTableCell release];
    [nameLabel release];
    [numLabel release];
    [pictureButton release];
    [super dealloc];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    switch ( section )
    {
        case 0:
            return 1;
        case 1:
        {
            if ( isActivated )
            {
                return 2;
            }
            return 2;
        }
            break;
        case 2:
            return 1;
        case 3:
            return 4;
        default:
            break;
    }
    
    return 0;
}
- (void) changeOn :(UISwitch*)sender{
    BOOL reminded = sender.on;
    extern BOOL showPersonImage;
    showPersonImage = reminded;
    NSUserDefaults * gUD = [NSUserDefaults standardUserDefaults];
    if(showPersonImage)
      [gUD setObject:@"true" forKey:@"showPersonImage"];  
    else
        [gUD setObject:@"false" forKey:@"showPersonImage"];
    
    [gUD synchronize];
    NSLog(@"%d",reminded);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    
    NSString *styleValue1CellIdent = @"StyleValue1Cell";
    NSString *styleDefaultCellIdent = @"StyleDefaultCell";
    switch ( indexPath.section )
    {
        case 0: //激活注册
        {
            if ( !isActivated )    //未激活
            {
                cell = [tableView dequeueReusableCellWithIdentifier: styleValue1CellIdent];
                
                if ( cell == nil )
                {
                    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:styleValue1CellIdent] autorelease];
                }
                
                cell.textLabel.text = @"激活注册";
                cell.detailTextLabel.font = [UIFont systemFontOfSize:14];
                cell.detailTextLabel.text = @"未激活";
                cell.imageView.image = [UIImage imageNamed: kActivateCellPng];
                cell.imageView.highlightedImage = [UIImage imageNamed: kActivateCellOnPng];
            } 
            else
            {
                NSString *accountCellIdent = @"AccountCell";
                cell = [tableView dequeueReusableCellWithIdentifier: accountCellIdent];
                
                if ( cell == nil )
                {
                    cell = self.accountTableCell;
                }
                if ( [[MyClass getInstance].userName length] != 0 )
                {
                    self.nameLabel.textColor = [UIColor blackColor];
                    self.nameLabel.text = [MyClass getInstance].userName ;
                }
                
                self.numLabel.text = @"";
                
                //[self.pictureButton setImage:[UIImage imageWithContentsOfFile:[_modelEngine getUserImagePath]] forState:UIControlStateNormal];
                

            }
        }
            break;
        case 1: 
        {
            cell = [tableView dequeueReusableCellWithIdentifier: styleDefaultCellIdent];
            
            if ( cell == nil )
            {
                cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:styleDefaultCellIdent] autorelease];
            }
            for (UIView *subview in cell.subviews) {
                if (subview.tag == 1001)              
                    [subview removeFromSuperview];
            }
            if ( indexPath.row == 0 )   //通讯录备份和恢复
            {
                cell.textLabel.text = @"更换token";
                cell.imageView.image = [UIImage imageNamed: kBackupCellPng];
                cell.imageView.highlightedImage = [UIImage imageNamed: kBackupCellOnPng];
            }
            else  //头像
            {
                cell.textLabel.text = @"头像显示";
                cell.imageView.image = [UIImage imageNamed: @"personal_icon_08b.png"];
                UISwitch *sw;
                sw = [[UISwitch alloc] initWithFrame:CGRectMake(220, 10, 60, 24)];
                sw.tag = 1001;
                extern BOOL showPersonImage;
                sw.on = showPersonImage;
                [sw addTarget:self action:@selector(changeOn:) forControlEvents:UIControlEventValueChanged];

                [cell addSubview:sw];
                [sw release];
            }
        }
            break;
        case 2:
        {
            if ( indexPath.row == 0 )   //推送通知
            {
                cell = [tableView dequeueReusableCellWithIdentifier: styleValue1CellIdent];
                
                if ( cell == nil )
                {
                    cell = [[[UITableViewCell alloc] initWithStyle: UITableViewCellStyleValue1 reuseIdentifier:styleValue1CellIdent] autorelease];
                }
                
                cell.textLabel.text = @"推送通知";
                cell.detailTextLabel.font = [UIFont systemFontOfSize:14];
                
                NSUInteger rntypes = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
                
                if ( rntypes == UIRemoteNotificationTypeNone )
                {
                    cell.detailTextLabel.text = @"推送通知已关闭";
                }
                else
                {
                    cell.detailTextLabel.text = @"推送通知已开启";
                }
                
                cell.imageView.image = [UIImage imageNamed: kPushCellPng];
                cell.imageView.highlightedImage = [UIImage imageNamed: kPushCellOnPng];
                cell.accessoryType =  UITableViewCellAccessoryDisclosureIndicator;
            }
//            else    //推荐给好友
//            {
//                cell = [tableView dequeueReusableCellWithIdentifier: styleDefaultCellIdent];
//                
//                if ( cell == nil )
//                {
//                    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:styleDefaultCellIdent] autorelease];
//                }
//                
//                cell.textLabel.text = @"推荐给好友";
//                cell.imageView.image = [UIImage imageNamed: kRecommendCellPng];
//                cell.imageView.highlightedImage = [UIImage imageNamed: kRecommendCellOnPng];
//                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
//            }
        }
            break;
        case 3:
        {
            cell = [tableView dequeueReusableCellWithIdentifier:styleDefaultCellIdent];
            
            if ( cell == nil )
            {
                cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:styleDefaultCellIdent] autorelease];
            }
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

            if ( indexPath.row == 0 )   //产品介绍
            {
                cell.textLabel.text = @"产品介绍";
                cell.imageView.image = [UIImage imageNamed: kProductGuidPng];
                cell.imageView.highlightedImage = [UIImage imageNamed: kProductGuidOnPng];
            }
            else if ( indexPath.row == 1 )  //意见反馈
            {
                cell.textLabel.text = @"意见反馈";
                cell.imageView.image = [UIImage imageNamed: kFeedBackCellPng];
                cell.imageView.highlightedImage = [UIImage imageNamed: kFeedBackCellOnPng];
            }
            else if(indexPath.row == 2)   //帮助
            {
                cell.textLabel.text = @"帮助";
                cell.imageView.image = [UIImage imageNamed: kAboutCellPng];
                cell.imageView.highlightedImage = [UIImage imageNamed: kAboutCellOnPng];
            }
            else    //关于
            {
                cell.textLabel.text = @"关于";
                cell.imageView.image = [UIImage imageNamed: kBoutiqueCellPng];
                cell.imageView.highlightedImage = [UIImage imageNamed: kBoutiqueCellOnPng];
            }
        }
            break;
        default:
            break;
    }
    [cell setSelectionStyle: UITableViewCellSelectionStyleGray];
    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch ( indexPath.section )
    {
        case 0: //一键激活
        {
            if ( !isActivated )    //未激活
            {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您是否确定激活" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                
                alert.tag = ActivateAlertTag;
                [alert show];
                [alert release];
            } 
            else  //已激活，显示的为手机号
            {
                return;
            }
        }
            break;
        case 1:
        {
            if ( indexPath.row == 0 )    //通讯录备份页面
            {
                NSDictionary* dict = [[MyClass getInstance] refreshToken];   
                NSString* str = [NSString stringWithFormat:@"%@", [dict objectForKey:@"code"]];
                if ([str intValue]==0)
                { 
                    NSUserDefaults * gUD = [NSUserDefaults standardUserDefaults];
                    [gUD synchronize];
                    NSString* str = [dict objectForKey:@"token"];
                    [gUD setObject: str forKey:@"token"]; 
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您是否确定激活" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                    alert.tag = ActivateAlertTag;
                    [alert show];
                    [alert release];
                }
                else
                {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"更换token失败！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                    alert.tag = ActivateAlertTag;
                    [alert show];
                    [alert release];
                }
                
            
                self.hidesBottomBarWhenPushed = YES;
               // [self.navigationController pushViewController:backupView animated:YES];
               // [backupView release];
                self.hidesBottomBarWhenPushed = NO;
            }
            else    //免费短信查询，只有激活用户才有此项
            {
               
            }
        }
            break;
        case 2:
        {
            if ( indexPath.row == 0 )   //推送通知
            {
//                self.hidesBottomBarWhenPushed = YES;
//                PushSettingViewController *pushSettingView = [[PushSettingViewController alloc] initWithNibName:@"PushSettingViewController" bundle:nil];
//                
//                [self.navigationController pushViewController:pushSettingView animated:YES];
//                [pushSettingView release];
//                self.hidesBottomBarWhenPushed = NO;
            }
            else  //推荐给好友
            {
                //调用短信界面发送短信	
//                NSString *url = @"http://www.bbest100.com";    //从服务器获取
//                NSString *body = [[NSString alloc] initWithFormat:@"和我一起使用吧，超强的管理功能，下载:%@", url];
//                BOOL canSendSMS = [CommTools callMessageCompose:self bodyOfMessage:body numOfMessage:nil];
//                
//                if ( !canSendSMS ) //4.0以下版本不支持在程序中调用短信界面
//                {
//                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"不支持发送短信功能，请手动编辑短信" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//                    alert.tag = SmsNotSupportAlertTag;
//                    
//                    [alert show];
//                    [alert release];
//                }
//                
//                [body release];
            }
        }
            break;
        case 3:
        {
            if ( indexPath.row == 0 )           //产品介绍
            {
                FirstLauchViewController* productGuidView = [[FirstLauchViewController alloc] init];
                productGuidView.isPushed = YES;
                [self.navigationController pushViewController:productGuidView animated:YES];
                [productGuidView release];
            }
            else if ( indexPath.row == 1 )      //意见反馈
            {
                self.hidesBottomBarWhenPushed = YES;
                FeedbackViewController *feedbackView = [[FeedbackViewController alloc] initWithNibName:@"FeedbackViewController" bundle:nil];
                [self.navigationController pushViewController:feedbackView animated:YES];
                [feedbackView release];
                self.hidesBottomBarWhenPushed = NO;
            }
            else if ( indexPath.row == 2 )      //帮助
            {
                self.hidesBottomBarWhenPushed = YES;
                HelpViewController *aboutView = [[HelpViewController alloc] init];
                [self.navigationController pushViewController:aboutView animated:YES];
                [aboutView release];
                self.hidesBottomBarWhenPushed = NO;
            }
            else if ( indexPath.row == 3 )      //关于
            {
                self.hidesBottomBarWhenPushed = YES;
                AboutViewController *aboutView = [[AboutViewController alloc] init];
                [self.navigationController pushViewController:aboutView animated:YES];
                [aboutView release];
                self.hidesBottomBarWhenPushed = NO;
            }
        }
            break;
        default:
            break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ( indexPath.section == 0 && isActivated )
    {
        return 90;
    }
    
    return 44;
}

#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch ( alertView.tag )
    {
        case ActivateAlertTag:
        {
            if ( buttonIndex == 1 ) //确定
            {
                [self setHidesBottomBarWhenPushed:YES];

            }
        }
            break;
        default:
            break;
    }
}



#pragma mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if ( buttonIndex == actionSheet.cancelButtonIndex )
    {
        return;
    }
    
    switch ( buttonIndex )
    {
        case 0:     //相册图片
        {
            isSavedToAlbum = NO;
            
            UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
            ipc.sourceType =  UIImagePickerControllerSourceTypePhotoLibrary;
            ipc.delegate = self;
            ipc.allowsEditing = NO;
            [self presentModalViewController:ipc animated:YES];	
        }
            break;
        case 1:     //拍照
        {
            if ( [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera] )  //判断设备是否支持拍照功能
            {
                isSavedToAlbum = YES;
                
                UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
                ipc.sourceType =  UIImagePickerControllerSourceTypeCamera;
                ipc.delegate = self;
                [self presentModalViewController:ipc animated:YES];	
            }
            else
            {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"该设备不支持拍照功能" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
                
                [alert show];
                [alert release];
            }
        }
            break;
        default:
            break;
    }
}

#pragma mark ImagePicker

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo; 
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
    
    if ( !error )
    {
        [alert setMessage:@"Image written to photo album"];
    }
	else
    {
        NSString *msg = [[NSString alloc] initWithFormat:@"Error writing to photo album: %@", [error localizedDescription]];
		[alert setMessage: msg];
        [msg release];
    }
    
    [alert show];
    [alert release];
}

- (NSString *) findUniqueSavePath
{
	int i = 1;
	NSString *path; 
    
	do 
    {
		// iterate until a name does not match an existing file
	    path = [NSString stringWithFormat:@"%@/Documents/IMAGE_%04d.PNG", NSHomeDirectory(), i++];
	} while ([[NSFileManager defaultManager] fileExistsAtPath:path]);
	
	return path;
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"] ;
    [pictureButton setBackgroundImage:image forState:UIControlStateNormal];
    
    //Save the image to the album
    if ( isSavedToAlbum )
    {
        UIImageWriteToSavedPhotosAlbum( image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil );
    }
    
	[self dismissModalViewControllerAnimated:YES];
	[picker release];
    
    //将图片存到应用程序的document目录下
    NSString *path = [self findUniqueSavePath];
    [UIImagePNGRepresentation(image) writeToFile: path atomically:YES];
   // [_modelEngine setUserImagePath: path];
}

@end
